<?php
namespace app\common\widgets;

use Yii;
use \yii\helpers\ArrayHelper;
/**
 * 系统助手类
 *
 * @author        Terry<admin@huicms.cn>
 * @copyright     Copyright (c) 2007-2014 HuiCMS. All rights reserved.
 * @link          http://www.huicms.cn
 * @package       HuiCMS.Tools
 * @date          2014-04-04
 * @version       v1.0
 */
class Tools {

    static $result = null;
    /**
     * PHP发送请求
     * @author Terry <admin@huicms.cn>
     * @date 2013-05-14
     * @param string $url 请求地址
     */
    static public function location($url){
        echo "<script language='javascript'>window.location.href='{$url}';</script>";
    }

    /**
     * PHP发送异步请求
     * @author Terry <admin@huicms.cn>
     * @date 2013-05-14
     * @param string $url 请求地址
     * @param array $param 请求参数
     * @param string $httpMethod 请求方法GET或者POST
     * @return boolean
     * @link http://www.thinkphp.cn/code/71.html
     */
    static public function makeRequest($url, $param, $httpMethod = 'GET') {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        if ($httpMethod == 'GET') {
            curl_setopt($oCurl, CURLOPT_URL, $url . "?" . http_build_query($param));
            curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        } else {
            curl_setopt($oCurl, CURLOPT_URL, $url);
            curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($oCurl, CURLOPT_POST, 1);
            curl_setopt($oCurl, CURLOPT_POSTFIELDS, http_build_query($param));
        }

        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return FALSE;
        }
    }

    /**
     * 获取客户端IP地址
     */
    static public function getClientIP() {
        static $ip = NULL;
        if ( $ip !== NULL )
            return $ip;
        if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
            $arr = explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] );
            $pos = array_search( 'unknown', $arr );
            if ( false !== $pos )
                unset( $arr[$pos] );
            $ip = trim( $arr[0] );
        } elseif ( isset( $_SERVER['HTTP_CLIENT_IP'] ) ) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $ip = ( false !== ip2long( $ip ) ) ? $ip : '0.0.0.0';
        return $ip;
    }


    /**
     * 循环创建目录
     * @param $dir  目录
     * @param $mode 权限
     * @author Terry<admin@huicms.cn>
     * @date 2014-04-04
     * @version v1.0
     */
    static public function mkdir( $dir, $mode = 0777 ) {

        $aimUrl = str_replace('', '/', $dir);
        $aimDir = '';
        $arr = explode('/', $aimUrl);
        $result = true;
        foreach ($arr as $str) {
            $aimDir .= $str . '/';
            if (!file_exists($aimDir)) {
                $result = mkdir($aimDir, $mode);
            }
        }
        return $result;
    }

    /**
     * 字符截取
     *
     * @param $string
     * @param $length
     * @param $dot
     */
    public static function cutstr( $string, $length, $dot = '...', $charset = 'utf-8' ) {
        if ( strlen( $string ) <= $length )
            return $string;

        $pre = chr( 1 );
        $end = chr( 1 );
        $string = str_replace( array ( '&amp;' , '&quot;' , '&lt;' , '&gt;' ), array ( $pre . '&' . $end , $pre . '"' . $end , $pre . '<' . $end , $pre . '>' . $end ), $string );

        $strcut = '';
        if ( strtolower( $charset ) == 'utf-8' ) {

            $n = $tn = $noc = 0;
            while ( $n < strlen( $string ) ) {

                $t = ord( $string[$n] );
                if ( $t == 9 || $t == 10 || ( 32 <= $t && $t <= 126 ) ) {
                    $tn = 1;
                    $n ++;
                    $noc ++;
                } elseif ( 194 <= $t && $t <= 223 ) {
                    $tn = 2;
                    $n += 2;
                    $noc += 2;
                } elseif ( 224 <= $t && $t <= 239 ) {
                    $tn = 3;
                    $n += 3;
                    $noc += 2;
                } elseif ( 240 <= $t && $t <= 247 ) {
                    $tn = 4;
                    $n += 4;
                    $noc += 2;
                } elseif ( 248 <= $t && $t <= 251 ) {
                    $tn = 5;
                    $n += 5;
                    $noc += 2;
                } elseif ( $t == 252 || $t == 253 ) {
                    $tn = 6;
                    $n += 6;
                    $noc += 2;
                } else {
                    $n ++;
                }

                if ( $noc >= $length ) {
                    break;
                }

            }
            if ( $noc > $length ) {
                $n -= $tn;
            }

            $strcut = substr( $string, 0, $n );

        } else {
            for ( $i = 0; $i < $length; $i ++ ) {
                $strcut .= ord( $string[$i] ) > 127 ? $string[$i] . $string[++ $i] : $string[$i];
            }
        }

        $strcut = str_replace( array ( $pre . '&' . $end , $pre . '"' . $end , $pre . '<' . $end , $pre . '>' . $end ), array ( '&amp;' , '&quot;' , '&lt;' , '&gt;' ), $strcut );

        $pos = strrpos( $strcut, chr( 1 ) );
        if ( $pos !== false ) {
            $strcut = substr( $strcut, 0, $pos );
        }
        return $strcut . $dot;
    }

    /**
     * 获得来源类型 post get
     * @author Terry<admin@huicms.cn>
     * @date 2014-04-04
     * @return unknown
     */
    static public function method() {
        return strtoupper( isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : 'GET' );
    }

    /**
     * 引用字符串
     * @param  $string
     * @param  $force
     * @author Terry<admin@huicms.cn>
     * @date 2014-04-04
     * @return string
     */
    static public function addslashes($string, $force = 1) {
        if(is_array($string)) {
            foreach($string as $key => $val) {
                $string[$key] = self::addslashes($val, $force);
            }
        } else {
            $string = addslashes($string);
        }
        return $string;
    }

    /**
     * 转换XML文档为数组
     *
     * @author Terry<admin@huicms.cn>
     * @date 2014-04-01
     * @param string xml内容
     * @return mixed 返回的数组，如果失败，返回false
     */
    static public function xmlWx2array($xml) {
        $xml = (Array)simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
        return $xml;
    }

    /**
     * 转换XML文档为数组
     *
     * @author Terry<admin@huicms.cn>
     * @date 2014-04-01
     * @param string xml内容
     * @return mixed 返回的数组，如果失败，返回false
     */
    static public function xml2array($xml) {

        $xml = (Array)simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
        return self::simplexml2array($xml);

    }

    /**
     * 转换XML文档为数组（辅助方法）
     *
     * @author Terry<admin@huicms.cn>
     * @date 2014-04-01
     * @param string xml内容
     * @return mixed 返回的数组，如果失败，返回false
     */
    static public function simplexml2array($a) {

        if (is_object($a)) {
            settype($a, "array");
        }
        foreach ($a as $k=>$v) {
            if ((count($a)==1) && ($k=="_item_")) {
                if (is_array($v)) {
                    $a = simplexml2array($v);
                }
                elseif (is_object($v)) {
                    $a = simplexml2array($v);
                }
                else {
                    $a = array($v);
                }
            }
            else {
                if (is_array($v)) {
                    if (count($v)) {
                        $a[$k] = simplexml2array($v);
                    }
                    else {
                        $a[$k] = "";
                    }
                }
                elseif (is_object($v)) {
                    if (count($v)) {
                        $a[$k] = simplexml2array($v);
                    }
                    else {
                        $a[$k] = "";
                    }
                }
            }
        }
        return $a;
    }

    /**
     * 根据打态返回相应的css
     * @param string $status  状态编号
     * @return string
     **/
    public static function status($status){
        $data = array();
        switch($status){
            case '0':
                $data['style'] = 'label label-red';
                $data['msg'] = '禁用';
                break;
            case '1':
                $data['style'] = 'label label-satgreen';
                $data['msg'] = '启用';
                break;
        }
        return $data;
    }

    /**
     * 获取错误数组
     * @param string $code 错误编码
     * @param string $msg  错误
     * @param array $data
     * @return array
     */
    public static function getError($code = '',$msg = '',$data = array()) {
        $tmp = array();
        $tmp['code'] = $code;
        $tmp['msg']  = $msg;
        $tmp['data'] = $data;
        return $tmp;
    }

    /**
     *
     * 解析支付方式名称
     * @params string $key 支付方式类型
     * @author Terry<admin@huicms.cn>
     * @date 2014-05-28
     */
    static public function paymentName($key){
        $params = array(
            'Alipay'    => '支付宝',
            'Chinapay'    => '银联全民付',
            'Tenpay'    => '财付通',
            'Weipay'    => '微信支付'
        );
        return $params[$key];
    }

    /**
     *
     * 支付方式LOGO
     * @params string $key 支付方式类型
     * @author Terry<admin@huicms.cn>
     * @date 2014-05-28
     */
    static public function paymentLogo($key){
        $params = array(
            'alipay'    => 'z.jpg',
            'chinapay'    => 'l.jpg',
            'weipay'    => 'w.jpg',
        );
        return $params[$key];
    }

    /**
     * @brief 随机生成字符串函数
     * @param int $len 要生成的长度
     * @param string $type 生成字符串的类型
     * @return String 随机生成字符
     */
    static public function random($len=6,$type='mix') {
        $len = intval($len);
        if($len >32) $len = 32;
        $str  = '';
        $attr = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','g','m','p','t','z','c');
        shuffle($attr);
        $int_attr = array('0','1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6','7','8','9','5','9');
        shuffle($int_attr);
        $attr     = implode($attr);
        $int_attr = implode($int_attr);
        switch($type) {
            case 'int': $str= $int_attr;break;
            case 'char': $str = $attr;break;
            default: $str = md5(uniqid(mt_rand(), true)); break;
        }
        return substr($str,0,$len);
    }

    static public function unique($param) {
        $arr_param = array_unique($param);
        $ary_param = array();
        foreach($arr_param as $values) {
            $ary_param[] = $values;
        }
        return $ary_param;
    }

    static public function requestUri() {
        if (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
            $uri = $_SERVER['HTTP_X_REWRITE_URL'];
        }elseif (isset($_SERVER['REQUEST_URI'])) {
            $uri = $_SERVER['REQUEST_URI'];
        }elseif (isset($_SERVER['ORIG_PATH_INFO'])){
            $uri = $_SERVER['ORIG_PATH_INFO'];
            if (! empty($_SERVER['QUERY_STRING'])){
                $uri .= '?' . $_SERVER['QUERY_STRING'];
            }
        }else{
            $uri = '';
        }
        return $uri;
    }

    /**
     * 计算分页
     * @param int $count 总记录
     * @param array $page 当前页码
     * $page = array(
    'page'=>2//读取页码
     *     'size'=>10,//每页大小，默认15
     * )
     * @return array
     */
    static public function getPage($count = 0,$pages) {
        $page = array('size'=>0,'count'=>0,'page'=>0,'total'=>0,'list'=>0);
        $page['count'] = $count;

        //每页大小
        $page['size']  = intval($pages['size']) <= 0 ? 15 : $pages['size'];

        //计算总页数
        $page['total'] = ceil($page['count']/$page['size']);

        //计算当前页
        $curpage = intval($pages['page']) <= 0 ? 1 : intval($pages['page']);
        $page['page'] = $curpage;

        //计算读取的开始记录
        $startrow = $page['size'] * ($page['page'] - 1) ;
        $startrow  =  $startrow < 0 ? 0 : $startrow;
        return ['offset'=>$startrow,'limit'=>$page['size']];
    }

    /**
     * 格式化分页
     * @param array $data
     * @param int $count
     */
    static public function formatPage($data = [],$count = 0) {
        return ['datalist'=>$data,'total_results'=>$count];
    }

    /**
     * 发送Json
     */
    static public function sendJson($code,$msg, $url = '',$data = []) {
        $temp = [];
        $temp['status'] = $code;
        $temp['url'] = $url;
        $temp['message']  = $msg;
        $temp['data'] = $data;
        print json_encode($temp);
        exit;
    }

    static public function hpIconv($in_charset,$out_charset,$str){
        if(is_array($str)){
            foreach($str as $k=>$v){
                
                  $str[$k]=iconv($in_charset,$out_charset,$v);
                
            }
            return $str;
        }else{
           
            return iconv($in_charset,$out_charset,$str);
           
        }    
    }

    static public function httpPostMedia($url,$post_data,$filename,$filetype) {
        //    初始化
        $ch = curl_init();

        $file = $post_data['media'];
        if (!function_exists('curl_file_create')) {
            $post_data['media']  ="@".$file.";filename=" .$filename.";type=".$filetype;
        }else{
            $post_data['media'] =   curl_file_create($file);
        }
        //    设置变量
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);//参数设置，是否显示头部信息，1为显示，0为不显示
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );//是直接输出结果到浏览器，还是return结果

        //表单数据，是正规的表单设置值为非0
        curl_setopt($ch, CURLOPT_POST, 1);

        curl_setopt($ch, CURLOPT_TIMEOUT, 100);//设置curl执行超时时间最大是多少

        //使用数组提供post数据时，CURL组件大概是为了兼容@filename这种上传文件的写法，
        //默认把content_type设为了multipart/form-data。虽然对于大多数web服务器并
        //没有影响，但是还是有少部分服务器不兼容。本文得出的结论是，在没有需要上传文件的
        //情况下，尽量对post提交的数据进行http_build_query，然后发送出去，能实现更好的兼容性，更小的请求数据包。
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_INFILESIZE,filesize($file)); //这句非常重要，告诉远程服务器，文件大小，查到的是前辈的文章
        //     执行并获取结果
        $res = curl_exec($ch);
        if($res === FALSE)
        {
            echo "<br/>","  cUrl Error:".curl_error($ch);
        }
        //    释放cURL句柄
        curl_close($ch);

        return $res;
    }

    static public function _httpPost($url, $postData, $timeout = 500) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL,$url);

        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);


        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        $res = curl_exec($ch);
        curl_close($ch);

        return $res;
    }

    static public function _httpGet($url, $timeout=500) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    static public function checkUrl($url){
        if(!preg_match('/http:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is',$url)){
            return false;
        }
        return true;
    }

    static public function mdir($destFolder) {
        if (file_exists($destFolder) || $destFolder == './' || $destFolder == '../')
        {
            return true;
        }

        $dirname = '';
        $folders = explode('/', $destFolder);
        foreach ($folders as $folder)
        {
            $dirname .= $folder . '/';
            if ($folder != '' && $folder != '.' && $folder != '..' && ! file_exists($dirname))
            {
                if (!@mkdir($dirname))
                {
                    return false;
                }
            }
        }
        @chmod($destFolder, 0777);

        return true;
    }

    /**
     * 	作用：array转xml
     */
    public function arrayToXml($arr) {
        $xml = "<xml>";
        foreach ($arr as $key=>$val) {
            if (is_numeric($val)) {
                $xml.="<".$key.">".$val."</".$key.">";
            }
            else {
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        //echo $xml;
        return $xml;
    }

    /**
     * api 发送请求
     * 如果新模块或新接口，请配置api地址
     * Yii::$app->params['api'];
     *<B>示例：</B>
     *<pre>
     * 调用微客接口
     * $data = array(
     *    'name'=>'232',
     *    'title'=>'23232'
     * );
     *  common\widgets\Tools::api('site/index',$data,'weike');
     *</pre>
     * @param string $url 地址
     * @param array $data 发送数据
     * @param string $module 模块
     * @return bool|array
     * false: 表示接口请求失败，或返回内容json 解析失败
     * array: 返回内容
     */
    static public function api($url = '',$data = array(),$module = '',$options = '')
    {
        $api = Yii::$app->params['api'];

        if (false == empty ( $module )) {
            $base = $api [$module];
        } else {
            // 默认的请求URL
            $base = $api ['default'];
        }

        $api_url = $base . $url;
        $curl_result = self::request($api_url,$data,$options);
        if ($curl_result === false) {
            return false;
        }
        return $curl_result;

    }

    static public function request($url,$data,$options = array())
    {
        $_options = array(
            'method'=>'POST',
            'timeout'=> 2, // http 连接超时 单位 秒
            'receive_timeout'=> 10,// 接收数据超时 单位 秒
        );
        // 如果设置了响应超时，-1表示不限，否则以设置为准
        if (true == isset ( $options ['receive_timeout'] )) {
            if ('-1' == $options ['receive_timeout']) {
                unset ( $_options ['receive_timeout'] );
            } else {
                $_options ['receive_timeout'] = $options ['receive_timeout'];
            }
            unset ( $options ['receive_timeout'] );
        }
        if (is_array($options)) {
            $_options = array_merge($_options,$options);
        } else {
            if (!empty($options)) {
                $_options['method'] = $options;
            }
        }

        if ($_options['method'] == 'GET') {
            if (!empty($data)) {
                $url = strpos($url,'?')  === false ? $url . '?' . http_build_query($data) : $url  . '&'. http_build_query($data);
            }
        }
        $curl_handle = curl_init();
        curl_setopt($curl_handle, CURLOPT_URL, $url);

        curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl_handle, CURLOPT_HEADER, false);

        $json_result = curl_exec($curl_handle);
        $errno = curl_errno($curl_handle);
        curl_close($curl_handle);
        if (!$errno) {
            $result = self::isJson($json_result) ? json_decode($json_result, true) : $json_result;
            if (is_null($result) || $result === false) {
                $result = false;
            }
        } else {
            $result = false;
        }
        return $result;
    }


    /**
     * 二维数组排序
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     *<B>示例：</B>
     *<pre>
     *  $array = array(
     * 		array('userId'=>'3','name'=>'admin3'),
     *      array('userId'=>'1','name'=>'admin1'),
     *      array('userId'=>'2','name'=>'admin2')
     * )
     * ArrayList::arraySort($array,'userId','desc');
     * 结果
     * 	 *  $array = array(
     * 		array('userId'=>'3','name'=>'admin3'),
     *      array('userId'=>'2','name'=>'admin2')
     * 		array('userId'=>'1','name'=>'admin1'),
     * )
     *</pre>
     * @param array $arr 源数组
     * @param string $key 数据项key
     * @param string $order 排序规则 desc 降序 asc 升序
     * @return int
     */
    static public function arraySort($arr, $key, $order = 'desc') {
        $keysvalue = $new_array = array();
        foreach ($arr as $k => $v) {
            $keysvalue[$k] = $v[$key];
        }

        if ($order == 'asc') {
            asort($keysvalue);
        } else {
            arsort($keysvalue);
        }

        reset($keysvalue);
        foreach ($keysvalue as $k => $v) {
            $new_array[$k] = $arr[$k];
        }

        return $new_array;
    }

    /**
     * 直接输出json
     * @param array $data 数据数组
     */
    static public function sendToJson($data = [],$boolExis = true) {
        print json_encode($data,true);
        exit;
    }

    /**
     * 输出格式化json 格式
     * @param string|array $error 错误编号
     * @param string $message 错误消息
     * @param string $data 错误数据
     * json = {error:'错误编号','message'=>'消息','data'=>'数据'}
     */
    static public function sendFormatJson($error = '',$message = '',$data = array()) {
        if (!is_array($error)) {
            $error = [
                'code' => $error,
                'message' => $message,
                'data' => $data,
            ];
        }
        $output = [];
        $output = ArrayHelper::merge($output, $error);

        self::sendToJson($output,false);
    }
    
     /**
     * CURL请求
     * @param $url
     * @param array $data
     * @param bool $is_post
     * @param array $header
     * @return mixed
     */
    static public function sub_curl($url, $data = array(), $is_post = false, $header = array('Content-Type:application/x-www-form-urlencoded')) {
        $ch = curl_init();
        if (!$is_post && !empty($data)) {
            $url = $url . '?' . http_build_query($data);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, $is_post);
        if ($is_post) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        if (!empty($header)) {
            // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        $info = curl_exec($ch);
        //$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $info;
    }
    
    /**
     * 数组分页函数 核心函数 array_slice
     * 用此函数之前要先将数据库里面的所有数据按一定的顺序查询出来存入数组中
     * $page  当前第几页
     * $array  查询出来的所有数组
     * $size 一页多少条数据
     * order 0 - 不变   1- 反序
     */
    public function page_array($page, $size,$array, $order) {
        $page = (empty($page)) ? '1' : $page; #判断当前页面是否为空 如果为空就表示为第一页面 
        $size = (empty($size)) ? '5' : $size;
        $start = ($page - 1) * $size; #计算每次分页的开始位置
        if ($order == 1) {
            $array = array_reverse($array);
        }
        $totals = count($array);
        $this->countpage = ceil($totals / $size); #计算总页面数
        $pagedata = array();
        $pagedata = array_slice($array, $start, $size);
        return $pagedata; #返回查询数据
    }

    static public function isJson($string) {
        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }

    static public function isWeixin() {
        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            return true;
        }
        return false;
    }

    /**
     * 根据业务模块定义处理订单返回结果
     */
    static public function getModulesCallFunc($moduleName) {
        $callFunc = '';
        switch($moduleName) {
            //预订下单
            case "COURSE":
                $callFunc = 'callbackOrderPay';
                break;
            //会员充值
            case "RECHARGE":
                $callFunc = "callbackPayRecharge";
                break;
            case "ADDORDER":
                $callFunc = "callbackPayOrder";
                break;
            default:
                break;
        }
        return $callFunc;
    }

    /**
     * 创建错误格式
     * @param string $error
     * @param string $message
     * @param array $data
     */
    public static function createError($error = '',$message = '',$data = array()) {
        $output = array();
        if (is_array($error)) {
            $output = $error;
        } else {
            $output['code'] = $error;
            $output['message'] = $message;
            $output['data'] = $data;
        }

        return $output;
    }

    /**
     * 创建随机字串
     *
     * @param integer $len 字串长度
     * @return string
     */
    public static function genRandomString($len = 16) {
        $chars = array(
            "a",
            "b",
            "c",
            "d",
            "e",
            "f",
            "g",
            "h",
            "i",
            "j",
            "k",
            "l",
            "m",
            "n",
            "o",
            "p",
            "q",
            "r",
            "s",
            "t",
            "u",
            "v",
            "w",
            "x",
            "y",
            "z",
            "A",
            "B",
            "C",
            "D",
            "E",
            "F",
            "G",
            "H",
            "I",
            "J",
            "K",
            "L",
            "M",
            "N",
            "O",
            "P",
            "Q",
            "R",
            "S",
            "T",
            "U",
            "V",
            "W",
            "X",
            "Y",
            "Z",
            "0",
            "1",
            "2",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8",
            "9");
        $charsLen = count($chars) - 1;
        shuffle($chars);
        $output = '';
        for ($i = 0; $i < $len; $i ++) {
            $output .= $chars[mt_rand(0, $charsLen)];
        }

        return $output;
    }

    /**
     * 存储ocs值
     *
     * @param string $str_key
     *        	存储key
     * @param mixed $mix_value
     *        	存储key对应值
     * @param int $int_expire
     *        	存储有效期，单位：秒，0表示永不过期
     * @return bool 存储成功返回true，失败返回false
     * @author Terry<admin@huicms.cn>
     * @version 1.0
     */
    public static function setOCS($str_key, $mix_value, $int_expire = '0') {
        $bool_set = false;
        $int_try_times = '0';
        $int_max_times = '3';
        // 如果存储失败，默认尝试三次
        while ( false === $bool_set && $int_try_times < $int_max_times ) {
            $bool_set = \Yii::$app->cache->set ( $str_key, $mix_value, $int_expire );
            $int_try_times ++;
        }
        return $bool_set;
    }

    /**
     * 获取指定key的ocs存储值
     *
     * @param string $str_key
     *        	存储key
     * @return mixed 存储key对应值（如果获取不到/过期/依赖变更则返回false）
     * @author Terry<admin@huicms.cn>
     * @version 1.0
     */
    public static function getOCS($str_key) {
        $mix_value = false;
        $int_try_times = '0';
        $int_max_times = '3';
        // 如果获取不到/过期/依赖变更，默认尝试三次
        while ( false === $mix_value && $int_try_times < $int_max_times ) {
            $mix_value = \Yii::$app->cache->get ( $str_key );
            $int_try_times ++;
        }
        return $mix_value;
    }

    /**
     * 删除指定key的ocs存储项
     *
     * @param string $str_key
     *        	存储key
     * @return bool 删除成功返回true，失败返回false
     * @author Terry<admin@huicms.cn>
     * @version 1.0
     */
    public static function deleteOCS($str_key) {
        $mix_value = Tools::getOCS ( $str_key );
        if (true == empty ( $mix_value )) {
            return true;
        }
        $bool_delete = false;
        $int_try_times = '0';
        $int_max_times = '3';
        // 如果删除失败，默认尝试三次
        while ( false === $bool_delete && $int_try_times < $int_max_times ) {
            $bool_delete = \Yii::$app->cache->delete ( $str_key );
            $int_try_times ++;
        }
        return $bool_delete;
    }

    public static function truncate_utf8_string($string, $length, $etc = '...')
    {
        $result = '';
        $string = html_entity_decode(trim(strip_tags($string)), ENT_QUOTES, 'UTF-8');
        $strlen = strlen($string);
        for ($i = 0; (($i < $strlen) && ($length > 0)); $i++)
        {
            if ($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, '0', STR_PAD_LEFT), '0'))
            {
                if ($length < 1.0)
                {
                    break;
                }
                $result .= substr($string, $i, $number);
                $length -= 1.0;
                $i += $number - 1;
            }
            else
            {
                $result .= substr($string, $i, 1);
                $length -= 0.5;
            }
        }
        $result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
        if ($i < $strlen)
        {
            $result .= $etc;
        }
        return $result;
    }

    /**
     * 计算两组经纬度坐标 之间的距离
     * @params $lat1 纬度1；
     * @params $lng1 经度1；
     * @params $lat2 纬度2；
     * @params $lng2 经度2；
     * @params $len_type （1:m or 2:km);
     * @return m or km
     * @version 1.0
     */
    public static function getDistance($lat1, $lng1, $lat2, $lng2, $len_type = 1, $decimal = 2) {
        $EARTH_RADIUS=6378.137;
        $PI=3.1415926;
        $radLat1 = $lat1 * $PI / 180.0;
        $radLat2 = $lat2 * $PI / 180.0;
        $a = $radLat1 - $radLat2;
        $b = ($lng1 * $PI / 180.0) - ($lng2 * $PI / 180.0);
        $s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
        $s = $s * $EARTH_RADIUS; $s = round($s * 1000);
        if ($len_type > 1) {
            $s /= 1000;
        }
        return round($s,$decimal);
    }

    /**
     * 时间格式化
     */
    static public function formatDate($time){
        $rtime = date ( "m-d H:i", $time );
        $htime = date ( "H:i", $time );

        $time = time () - $time;

        if ($time < 60) {
            $str = '刚刚';
        } elseif ($time < 60 * 60) {
            $min = floor ( $time / 60 );
            $str = $min . '分钟前';
        } elseif ($time < 60 * 60 * 24) {
            $h = floor ( $time / (60 * 60) );
            $str = $h . '小时前 ' . $htime;
        } elseif ($time < 60 * 60 * 24 * 3) {
            $d = floor ( $time / (60 * 60 * 24) );
            if ($d == 1)
                $str = '昨天 ' . $rtime;
            else
                $str = '前天 ' . $rtime;
        } else {
            $str = $rtime;
        }
        return $str;
    }

    /**
     * 求两个日期之间相差的天数
     * @param string $datetime1
     * @param string $datetime2
     * @return number
     */
    static public function diffBetweenTwoDays($datetime1, $datetime2) {
        $second1 = strtotime($datetime1);
        $second2 = strtotime($datetime2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return bcdiv(bcsub($second1, $second2, 3), 86400, 3);
    }

    /**
     * 求距离
     */
    static public function Distance($distance) {
        $str_distance = $distance / 1000;
        return $str_distance;
    }

    static public function Dirthday($birthday) {
        $age = $birthday;
        if($age === false) {
            return false;
        }
        list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age));
        $now = strtotime("now");
        list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now));
        $age = $y2 - $y1;
        if((int)($m2.$d2) < (int)($m1.$d1))
            $age -= 1;
        return $age;
    }

    static public function hideStr($string, $bengin = 0, $len = 4, $type = 0, $glue = "@") {
        if (empty($string))
            return false;
        $array = array();
        if ($type == 0 || $type == 1 || $type == 4) {
            $strlen = $length = mb_strlen($string);
            while ($strlen) {
                $array[] = mb_substr($string, 0, 1, "utf8");
                $string = mb_substr($string, 1, $strlen, "utf8");
                $strlen = mb_strlen($string);
            }
        }
        switch ($type) {
            case 1:
                $array = array_reverse($array);
                for ($i = $bengin; $i < ($bengin + $len); $i++) {
                    if (isset($array[$i]))
                        $array[$i] = "*";
                }
                $string = implode("", array_reverse($array));
                break;
            case 2:
                $array = explode($glue, $string);
                $array[0] = hideStr($array[0], $bengin, $len, 1);
                $string = implode($glue, $array);
                break;
            case 3:
                $array = explode($glue, $string);
                $array[1] = hideStr($array[1], $bengin, $len, 0);
                $string = implode($glue, $array);
                break;
            case 4:
                $left = $bengin;
                $right = $len;
                $tem = array();
                for ($i = 0; $i < ($length - $right); $i++) {
                    if (isset($array[$i]))
                        $tem[] = $i >= $left ? "*" : $array[$i];
                }
                $array = array_chunk(array_reverse($array), $right);
                $array = array_reverse($array[0]);
                for ($i = 0; $i < $right; $i++) {
                    $tem[] = $array[$i];
                }
                $string = implode("", $tem);
                break;
            default:
                for ($i = $bengin; $i < ($bengin + $len); $i++) {
                    if (isset($array[$i]))
                        $array[$i] = "*";
                }
                $string = implode("", $array);
                break;
        }
        return $string;
    }

    /*********************************************************************
    函数名称:encrypt
    函数作用:加密解密字符串
    使用方法:
    加密  :encrypt('str','E','nowamagic');
    解密  :encrypt('被加密过的字符串','D','nowamagic');
    参数说明:
    $string :需要加密解密的字符串
    $operation:判断是加密还是解密:E:加密 D:解密
    $key  :加密的钥匙(密匙);
     *********************************************************************/
    static public function encrypt($string, $operation, $key='') {
        $key=md5($key);
        $key_length=strlen($key);
        $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
        $string_length=strlen($string);
        $rndkey=$box=array();
        $result='';
        for($i=0;$i<=255;$i++)
        {
            $rndkey[$i]=ord($key[$i%$key_length]);
            $box[$i]=$i;
        }
        for($j=$i=0;$i<256;$i++)
        {
            $j=($j+$box[$i]+$rndkey[$i])%256;
            $tmp=$box[$i];
            $box[$i]=$box[$j];
            $box[$j]=$tmp;
        }
        for($a=$j=$i=0;$i<$string_length;$i++)
        {
            $a=($a+1)%256;
            $j=($j+$box[$a])%256;
            $tmp=$box[$a];
            $box[$a]=$box[$j];
            $box[$j]=$tmp;
            $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
        }
        if($operation=='D')
        {
            if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8))
            {
                return substr($result,8);
            }
            else
            {
                return'';
            }
        }
        else
        {
            return str_replace('=','',base64_encode($result));
        }
    }

    /**
     * 输出格式化json 格式
     * @param string|array $error 错误编号
     * @param string $message 错误消息
     * @param string $data 错误数据
     * json = {error:'错误编号','message'=>'消息','data'=>'数据'}
     */
    static public function sendFrontendFormatJson($error = '',$message = '',$data = array(), $url = '') {
        if (!is_array($error)) {
            $error = [
                'code' => $error,
                'msg' => $message,
                'data' => $data,
                'url' => $url,
            ];
        }
        $output = [];
        $output = ArrayHelper::merge($output, $error);

        self::sendToJson($output,false);
    }

    static public function curlGetHttp($url) {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36"); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }

    static public function curlGetImage($url) {
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt ( $ch, CURLOPT_URL, $url );
        ob_start ();
        curl_exec ( $ch );
        $return_content = ob_get_contents ();
        ob_end_clean ();

        $return_code = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
        return $return_content;
    }

    /**
     * 根据用户id生成6位随机码
     * @param $user_id
     * @param null $chars
     * @return string
     */
    static public function getRandomString($len, $chars=null)
    {
        if (is_null($chars)){
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        mt_srand(10000000 * (double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }
}
